package win.bitterwine.filter;

import org.smart4j.framework.util.StringUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Administrator on 2017/6/19 0019.
 */
@WebFilter(filterName="loginFilter",urlPatterns="/*")
public class LoginFilter implements Filter{

    private FilterConfig config;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");//解决中文乱码
        response.setContentType("text/html;charset=utf-8");
        HttpServletRequest req =(HttpServletRequest)request;
        //HttpSession session =req.getSession(true);
//        if(false){ //此处验证用户是否登录,是否拥有该路径的权限
//            RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
//            dispatcher.forward(request, response);
//            return;
//        }
        String path = req.getContextPath();
        String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path;
        String pathInfo = StringUtil.defaultIfEmpty(req.getPathInfo(), "");
        String url = basePath+req.getServletPath() + pathInfo;
        System.out.println("------>过滤器:"+url);

        //请求类型  如果是ajax请求响应头会有，x-requested-with；
//        if (req.getHeader("x-requested-with") != null
//                && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
//            PrintWriter out = null;
//            out = response.getWriter();
//            ObjectMapper mapper = new ObjectMapper();
//            Map<String,String> jsonMap = new HashMap<>();
//            jsonMap.put("rspCode", "logintimeout");
//            jsonMap.put("rspDesc", "登陆超时");
//            String json = mapper.writeValueAsString(jsonMap);//返回字符串
//            out.write(json);
//            out.flush();
//            System.out.println("ajax请求.......:" + url);
//        }


        //放行。让其走到下个链或目标资源中
        chain.doFilter(request,response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }
    @Override
    public void destroy() {
        System.out.println("过滤器销毁......");
    }
}
